package cn.lkx.serviceucenter.controller;

import cn.lkx.commonutils.JwtUtils;
import cn.lkx.servicebase.exceptionhandle.MyException;
import cn.lkx.serviceucenter.entity.UcenterMember;
import cn.lkx.serviceucenter.service.UcenterMemberService;
import cn.lkx.serviceucenter.utils.ConstantWxUtils;
import cn.lkx.serviceucenter.utils.HttpClientUtils;
import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

/**
 * 前台会员的 微信登录
 */
@Controller
@CrossOrigin
@RequestMapping("/api/ucenter/wx")
public class WxApiController {
    @Autowired
    UcenterMemberService memberService;

    //2、回调控制器，扫完码确认登录后自动执行 扫码自动注册并登录
    @GetMapping("callback")
    public String callback(String code,String state){ //微信认证服务器传来code 等值
        System.out.println(code+"===="+state);

        //2、使用httpclient发送请求，得到返回结果
        try {

            //1、拿着app_id密钥和code向微信的认证服务器发送请求换取access_token 和open_id
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";
            String accessTokenUrl = String.format(baseAccessTokenUrl,
                    ConstantWxUtils.WX_OPEN_APP_ID,
                    ConstantWxUtils.WX_OPEN_APP_SECRET,
                    code);
            //2、使用httpclient发送请求，得到返回结果
            String result = HttpClientUtils.get(accessTokenUrl);
            System.out.println("accessToken=============" + result);

            //3、解析返回的json字符串
            //使用Gson工具转换成map集合获取里边的 access_token open_id
            Gson gson = new Gson();
            HashMap map = gson.fromJson(result, HashMap.class);
            String access_token = (String) map.get("access_token");
            String openid = (String) map.get("openid");
            //先根据openid查询数据库是否存在该用户
            UcenterMember member = memberService.getMemberByOpenId(openid);

            if (member==null){ //为空才是注册

                //4、用access_token open_id访问固定地址，获得用户信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl  = String.format(baseUserInfoUrl, access_token, openid);
                String resultUserInfo = null;
                resultUserInfo  = HttpClientUtils.get(userInfoUrl);
                System.out.println("resultUserInfo==========" + resultUserInfo);
                //解析json
                HashMap mapUserInfo = gson.fromJson(resultUserInfo, HashMap.class);
                String nickname = (String)mapUserInfo.get("nickname");  //昵称
                String headimgurl = (String)mapUserInfo.get("headimgurl"); //头像
                //存储新用户到数据库
                member = new UcenterMember();
                member.setNickname(nickname);
                member.setOpenid(openid);
                member.setAvatar(headimgurl);
                memberService.save(member);

            }
            //使用JWT生成 token 传递前端，前端根据 token获取用户信息
            String jwtToken = JwtUtils.getJwtToken(member.getId(),member.getNickname());
            //跳转到首页，并显示登录信息
            return "redirect:http://localhost:3000?token="+jwtToken;
        } catch (Exception e) {
            throw new MyException(20001,"登录失败");
        }
    }
    //1、生成二维码
    @GetMapping("getWxCode")
    public String getWxCode(){
        //固定的地址
        //微信开放平台授权baseUrl %s相当于 ？ 占位符
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect"+
                "?appid=%s"+
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";
        //需要对redirect_url 进行 Encoder编码
        String redirectUrl = ConstantWxUtils.WX_OPEN_REDIRECT_URL;
        try {
            URLEncoder.encode(redirectUrl,"utf-8");
        } catch (UnsupportedEncodingException e) {
            throw new MyException(20001,"登录失败");
        }
        String url = String.format(
                baseUrl,
                ConstantWxUtils.WX_OPEN_APP_ID,
                redirectUrl,
                "lkx"
        );
        return "redirect:"+url;
    }
}
